package com.example.springboot.service;

import com.example.springboot.entity.*;
import com.example.springboot.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LaundryOptionService {
    private static final Logger logger = LoggerFactory.getLogger(LaundryOptionService.class);

    @Autowired
    private LaundryPackageMapper laundryPackageMapper;

    @Autowired
    private WaterAmountOptionMapper waterAmountOptionMapper;

    @Autowired
    private WashingProgramOptionMapper washingProgramOptionMapper;

    @Autowired
    private DetergentScentOptionMapper detergentScentOptionMapper;

    @Autowired
    private DryingProgramOptionMapper dryingProgramOptionMapper;

    // 获取所有洗衣选项（套餐和自定义选项）
    public Map<String, Object> getAllOptions(int packagePage, int waterPage, int washingPage, int scentPage, int dryingPage, int size, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        logger.info("Fetching all laundry options for role: {}, username: {}", role, decodedUsername);

        try {
            String adminRole = laundryPackageMapper.findAdminRoleByUsername(decodedUsername);
            if (!"super".equals(adminRole)) {
                logger.warn("Permission denied for username: {} with role: {}", decodedUsername, adminRole);
                throw new IllegalArgumentException("只有超级管理员可以访问此接口");
            }

            int packageOffset = Math.max((packagePage - 1) * size, 0);
            int waterOffset = Math.max((waterPage - 1) * size, 0);
            int washingOffset = Math.max((washingPage - 1) * size, 0);
            int scentOffset = Math.max((scentPage - 1) * size, 0);
            int dryingOffset = Math.max((dryingPage - 1) * size, 0);
            size = Math.max(size, 1);

            Map<String, Object> response = new HashMap<>();

            // 获取套餐
            List<LaundryPackage> packages = laundryPackageMapper.findAll(packageOffset, size);
            int packageTotal = laundryPackageMapper.getTotal();
            response.put("packages", packages);
            response.put("packageTotal", packageTotal);

            // 获取水量选项
            List<WaterAmountOption> waterOptions = waterAmountOptionMapper.findAll(waterOffset, size);
            int waterTotal = waterAmountOptionMapper.getTotal();
            response.put("waterOptions", waterOptions);
            response.put("waterTotal", waterTotal);

            // 获取洗涤程序选项
            List<WashingProgramOption> washingOptions = washingProgramOptionMapper.findAll(washingOffset, size);
            int washingTotal = washingProgramOptionMapper.getTotal();
            response.put("washingOptions", washingOptions);
            response.put("washingTotal", washingTotal);

            // 获取洗涤剂香味选项
            List<DetergentScentOption> scentOptions = detergentScentOptionMapper.findAll(scentOffset, size);
            int scentTotal = detergentScentOptionMapper.getTotal();
            response.put("scentOptions", scentOptions);
            response.put("scentTotal", scentTotal);

            // 获取烘干程序选项
            List<DryingProgramOption> dryingOptions = dryingProgramOptionMapper.findAll(dryingOffset, size);
            int dryingTotal = dryingProgramOptionMapper.getTotal();
            response.put("dryingOptions", dryingOptions);
            response.put("dryingTotal", dryingTotal);

            logger.info("Retrieved laundry options: packages={}, water={}, washing={}, scent={}, drying={}",
                    packages.size(), waterOptions.size(), washingOptions.size(), scentOptions.size(), dryingOptions.size());

            return response;
        } catch (Exception e) {
            logger.error("Failed to fetch laundry options for username: {}", decodedUsername, e);
            throw new RuntimeException("获取洗衣选项失败: " + e.getMessage());
        }
    }

    // 新增套餐
    public boolean createPackage(LaundryPackage laundryPackage, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        String adminRole = laundryPackageMapper.findAdminRoleByUsername(decodedUsername);
        if (!"super".equals(adminRole)) {
            throw new IllegalArgumentException("只有超级管理员可以操作");
        }

        int insertedRows = laundryPackageMapper.insert(laundryPackage);
        logger.info("Created new package, rows affected: {}", insertedRows);
        return insertedRows > 0;
    }

    // 更新套餐
    public boolean updatePackage(LaundryPackage laundryPackage, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        String adminRole = laundryPackageMapper.findAdminRoleByUsername(decodedUsername);
        if (!"super".equals(adminRole)) {
            throw new IllegalArgumentException("只有超级管理员可以操作");
        }

        int updatedRows = laundryPackageMapper.update(laundryPackage);
        logger.info("Updated package ID: {}, rows affected: {}", laundryPackage.getPackageId(), updatedRows);
        return updatedRows > 0;
    }

    // 删除套餐
    public boolean deletePackage(Long packageId, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        String adminRole = laundryPackageMapper.findAdminRoleByUsername(decodedUsername);
        if (!"super".equals(adminRole)) {
            throw new IllegalArgumentException("只有超级管理员可以操作");
        }

        int deletedRows = laundryPackageMapper.delete(packageId);
        logger.info("Deleted package ID: {}, rows affected: {}", packageId, deletedRows);
        return deletedRows > 0;
    }

    // 新增水量选项
    public boolean createWaterOption(WaterAmountOption waterOption, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        String adminRole = waterAmountOptionMapper.findAdminRoleByUsername(decodedUsername);
        if (!"super".equals(adminRole)) {
            throw new IllegalArgumentException("只有超级管理员可以操作");
        }

        int insertedRows = waterAmountOptionMapper.insert(waterOption);
        logger.info("Created new water option, rows affected: {}", insertedRows);
        return insertedRows > 0;
    }

    // 更新水量选项
    public boolean updateWaterOption(WaterAmountOption waterOption, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        String adminRole = waterAmountOptionMapper.findAdminRoleByUsername(decodedUsername);
        if (!"super".equals(adminRole)) {
            throw new IllegalArgumentException("只有超级管理员可以操作");
        }

        int updatedRows = waterAmountOptionMapper.update(waterOption);
        logger.info("Updated water option ID: {}, rows affected: {}", waterOption.getWaterOptionId(), updatedRows);
        return updatedRows > 0;
    }

    // 删除水量选项
    public boolean deleteWaterOption(Long waterOptionId, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        String adminRole = waterAmountOptionMapper.findAdminRoleByUsername(decodedUsername);
        if (!"super".equals(adminRole)) {
            throw new IllegalArgumentException("只有超级管理员可以操作");
        }

        int deletedRows = waterAmountOptionMapper.delete(waterOptionId);
        logger.info("Deleted water option ID: {}, rows affected: {}", waterOptionId, deletedRows);
        return deletedRows > 0;
    }

    // 新增洗涤程序选项
    public boolean createWashingOption(WashingProgramOption washingOption, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        String adminRole = washingProgramOptionMapper.findAdminRoleByUsername(decodedUsername);
        if (!"super".equals(adminRole)) {
            throw new IllegalArgumentException("只有超级管理员可以操作");
        }

        int insertedRows = washingProgramOptionMapper.insert(washingOption);
        logger.info("Created new washing option, rows affected: {}", insertedRows);
        return insertedRows > 0;
    }

    // 更新洗涤程序选项
    public boolean updateWashingOption(WashingProgramOption washingOption, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        String adminRole = washingProgramOptionMapper.findAdminRoleByUsername(decodedUsername);
        if (!"super".equals(adminRole)) {
            throw new IllegalArgumentException("只有超级管理员可以操作");
        }

        int updatedRows = washingProgramOptionMapper.update(washingOption);
        logger.info("Updated washing option ID: {}, rows affected: {}", washingOption.getProgramId(), updatedRows);
        return updatedRows > 0;
    }

    // 删除洗涤程序选项
    public boolean deleteWashingOption(Long programId, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        String adminRole = washingProgramOptionMapper.findAdminRoleByUsername(decodedUsername);
        if (!"super".equals(adminRole)) {
            throw new IllegalArgumentException("只有超级管理员可以操作");
        }

        int deletedRows = washingProgramOptionMapper.delete(programId);
        logger.info("Deleted washing option ID: {}, rows affected: {}", programId, deletedRows);
        return deletedRows > 0;
    }

    // 新增洗涤剂香味选项
    public boolean createScentOption(DetergentScentOption scentOption, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        String adminRole = detergentScentOptionMapper.findAdminRoleByUsername(decodedUsername);
        if (!"super".equals(adminRole)) {
            throw new IllegalArgumentException("只有超级管理员可以操作");
        }

        int insertedRows = detergentScentOptionMapper.insert(scentOption);
        logger.info("Created new scent option, rows affected: {}", insertedRows);
        return insertedRows > 0;
    }

    // 更新洗涤剂香味选项
    public boolean updateScentOption(DetergentScentOption scentOption, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        String adminRole = detergentScentOptionMapper.findAdminRoleByUsername(decodedUsername);
        if (!"super".equals(adminRole)) {
            throw new IllegalArgumentException("只有超级管理员可以操作");
        }

        int updatedRows = detergentScentOptionMapper.update(scentOption);
        logger.info("Updated scent option ID: {}, rows affected: {}", scentOption.getScentId(), updatedRows);
        return updatedRows > 0;
    }

    // 删除洗涤剂香味选项
    public boolean deleteScentOption(Long scentId, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        String adminRole = detergentScentOptionMapper.findAdminRoleByUsername(decodedUsername);
        if (!"super".equals(adminRole)) {
            throw new IllegalArgumentException("只有超级管理员可以操作");
        }

        int deletedRows = detergentScentOptionMapper.delete(scentId);
        logger.info("Deleted scent option ID: {}, rows affected: {}", scentId, deletedRows);
        return deletedRows > 0;
    }

    // 新增烘干程序选项
    public boolean createDryingOption(DryingProgramOption dryingOption, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        String adminRole = dryingProgramOptionMapper.findAdminRoleByUsername(decodedUsername);
        if (!"super".equals(adminRole)) {
            throw new IllegalArgumentException("只有超级管理员可以操作");
        }

        int insertedRows = dryingProgramOptionMapper.insert(dryingOption);
        logger.info("Created new drying option, rows affected: {}", insertedRows);
        return insertedRows > 0;
    }

    // 更新烘干程序选项
    public boolean updateDryingOption(DryingProgramOption dryingOption, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        String adminRole = dryingProgramOptionMapper.findAdminRoleByUsername(decodedUsername);
        if (!"super".equals(adminRole)) {
            throw new IllegalArgumentException("只有超级管理员可以操作");
        }

        int updatedRows = dryingProgramOptionMapper.update(dryingOption);
        logger.info("Updated drying option ID: {}, rows affected: {}", dryingOption.getDryingId(), updatedRows);
        return updatedRows > 0;
    }

    // 删除烘干程序选项
    public boolean deleteDryingOption(Long dryingId, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        String adminRole = dryingProgramOptionMapper.findAdminRoleByUsername(decodedUsername);
        if (!"super".equals(adminRole)) {
            throw new IllegalArgumentException("只有超级管理员可以操作");
        }

        int deletedRows = dryingProgramOptionMapper.delete(dryingId);
        logger.info("Deleted drying option ID: {}, rows affected: {}", dryingId, deletedRows);
        return deletedRows > 0;
    }

    private void validateInput(String role, String username) {
        if (username == null || username.trim().isEmpty()) {
            logger.error("Username is null or empty");
            throw new IllegalArgumentException("Username header is required");
        }
        if (role == null || role.trim().isEmpty()) {
            logger.error("Role is null or empty");
            throw new IllegalArgumentException("Role header is required");
        }
    }

    private String decodeUsername(String username) {
        if (username == null) {
            return null;
        }
        try {
            return URLDecoder.decode(username, "UTF-8");
        } catch (Exception e) {
            logger.warn("Failed to decode username: {}, using original value", username, e);
            return username;
        }
    }
}